package br.edu.unilasalle.simon_test.util;

import static com.google.common.base.Preconditions.checkNotNull;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.google.common.base.Predicate;

public class Predicates {

	public static Predicate<WebDriver> elementToBeClickable(final WebElement element) {
		return new Predicate<WebDriver>() {

			@Override
			public boolean apply(WebDriver input) {
				if (element.isDisplayed() && element.isEnabled()) {
					return true;
				} else {
					System.out.println("Teria dado erro. Displayed -> " + element.isDisplayed() + "| Enabled -> " + element.isEnabled());
					return false;
				}
			}

			@Override
			public String toString() {
				return "Predicates#elementClickable(" + element + ")";
			}

		};
	}

	public static Predicate<WebDriver> noActiveRequests(final WebElement element) {
		return new Predicate<WebDriver>() {

			@Override
			public boolean apply(WebDriver input) {
				String value = element.getAttribute("activeRequests");
				if (value == null || "0".equals(value)) {
					return true;
				} else {
					return false;
				}
			}

			@Override
			public String toString() {
				return "Predicates#elementClickable(" + element + ")";
			}

		};
	}

	public static Predicate<WebDriver> isPageLoaded(final String url) {
		return new Predicate<WebDriver>() {
			@Override
			public boolean apply(WebDriver driver) {
				String currentUrl = driver.getCurrentUrl();
				boolean hasElement = hasAnyElement(driver);
				checkNotNull(url, "URL deve ser informada.");

				if ((currentUrl.contains(url) || url.contains(currentUrl)) && hasElement) {
					return true;
				} else {
					System.out.println("Expected: " + url + " | Current: " + currentUrl + "| El? " + hasElement);
					return false;
				}
			}

			@Override
			public String toString() {
				return "Predicates#isPageLoaded(" + url + ")";
			}
		};
	}

	private static boolean hasAnyElement(WebDriver driver) {
		return !driver.findElements(By.tagName("body")).isEmpty();
	}
}
